package com.hythzx.ddns.service.impl;

import java.util.Optional;

import com.hythzx.ddns.service.IpService;
import com.hythzx.ddns.service.dto.emums.IpType;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import static org.slf4j.LoggerFactory.getLogger;

/**
 * 通过ifconfg.me 获取本机的公网IP
 * @author zhaoyuan
 */

@Component("ifconfig")
public class IfconfigServiceImpl implements IpService {

	private final RestTemplate restTemplate;

	private final Logger log = getLogger(IfconfigServiceImpl.class);

	private static final String IFCONFIG_ADDRESS = "https://ident.me";

	// 检测IPv6地址
	private static final String IFCONFIG_ADDRESS_V6 = "https://v6.ident.me";

	private static final String TYPE_IP_V4 = "A";

	private static final String TYPE_IP_V6 = "AAAA";

	public IfconfigServiceImpl(RestTemplate restTemplate) {
		this.restTemplate = restTemplate;
	}


	/**
	 * 获取本机的公网IP
	 * @return 公网IP
	 */
	@Override
	public Optional<String> getPublicIp() {
		return getIp(IFCONFIG_ADDRESS);
	}

	/**
	 * 获取本机的IPv6地址
	 *
	 * @return
	 */
	@Override
	public Optional<String> getPublicIpV6() {
		return getIp(IFCONFIG_ADDRESS_V6);
	}

	/**
	 * 获取指定类型的IP地址
	 *
	 * @param ipType
	 * @return
	 */
	@Override
	public Optional<String> getPublicIp(IpType ipType) {
		if (IpType.IpV4.equals(ipType)) return getIp(IFCONFIG_ADDRESS);
		if (IpType.IpV6.equals(ipType)) return getIp(IFCONFIG_ADDRESS_V6);
		return Optional.empty();
	}

	/**
	 * 获取指定的IP地址
	 *
	 * @param type 解析类型，A：IP v4， AAAA： IP v6
	 * @return
	 */
	@Override
	public Optional<String> getPublicIp(String type) {
		if (TYPE_IP_V4.equals(type)) return getIp(IFCONFIG_ADDRESS);
		if (TYPE_IP_V6.equals(type)) return getIp(IFCONFIG_ADDRESS_V6);
		return Optional.empty();
	}


	private Optional<String> getIp(String checkUrl) {
		log.debug("获取本机的公网IP");
		try {
			ResponseEntity<String> responseEntity = restTemplate.getForEntity(checkUrl, String.class);
			if(HttpStatus.OK.equals(responseEntity.getStatusCode()) && StringUtils.isNotEmpty(responseEntity.getBody())){
				String ipAddress = responseEntity.getBody();
				log.debug("公网IP获取成功，IP地址是: {}", ipAddress);
				return Optional.of(ipAddress);
			}
		}catch (Exception e) {
			log.warn("公网IP获取失败，失败信息是: [{}] - [{}]", e.getCause(), e.getMessage());
		}
		return Optional.empty();
	}
}
